package p3.view;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;

import generic.genetic.GeneticAlgorithm;

import javax.swing.JLabel;
import javax.swing.JPanel;

import org.math.plot.Plot2DPanel;
import org.math.plot.plotObjects.BaseLabel;
import org.math.plot.plotObjects.Line;

public class GA_Panel extends JPanel {

	private static final long serialVersionUID = 3373884873730805677L;
	private GeneticAlgorithm ga;
	private Plot2DPanel plot;
	private JLabel label;
		
	public GA_Panel(GeneticAlgorithm ga){
		
		this.ga = ga;
		
		this.setLayout(new BorderLayout());
		
		plot = new Plot2DPanel();
		plot.addLegend("SOUTH");
		
		label = new JLabel(ga.getBestChromosome().getString());
		
		this.add(plot, BorderLayout.CENTER);		
		this.add(label, BorderLayout.SOUTH);
						
	}
	
	public void paint(){
		
		plot.removeAllPlots();
		plot.removeAllPlotables();
		
		BaseLabel title = new BaseLabel(ga.getTitle(), Color.BLACK, 0.5, 1.1);
		title.setFont(new Font("Courier", Font.PLAIN, 14));
		plot.addPlotable(title);
		
		double[] x = new double[ga.getNum_generations()];
		double[] bestEver = new double[ga.getNum_generations()];
		double[] bestGen = new double[ga.getNum_generations()];
		double[] avgGen = new double[ga.getNum_generations()];
		
		for (int i=0;i<ga.getNum_generations();i++){
			x[i] = i;
			bestEver[i] = ga.bestEver.get(i);
			bestGen[i] = ga.bestGen.get(i);
			avgGen[i] = ga.avgGen.get(i);
		}
		
		plot.addLinePlot("Mejor absoluto", x, bestEver);
		plot.addLinePlot("Mejor de la generacion", x, bestGen);
		plot.addLinePlot("Media de la generacion", x, avgGen);
		
		
		plot.addPlotable(new Line(Color.CYAN, 
				new double[]{ga.firstGenBestChrom,plot.plotCanvas.base.baseCoords[1][1]},
				new double[]{ga.firstGenBestChrom,plot.plotCanvas.base.baseCoords[2][1]})				
		);
		
		
		
		plot.plotCanvas.resetBase();
		
		label.setText(ga.getBestChromosome().toString());
		this.validate();
		
	}
	
	public void run(){ ga.run(); paint(); }
	public void step() { ga.step(); paint();
	}
}
